package test.hxy.mongoSchoolSimple.dao;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import test.hxy.mongoSchoolSimple.model.Department;
import test.hxy.mongoSchoolSimple.model.Leader;

import java.util.ArrayList;
import java.util.List;

@Repository
public class DepartmentTwoDao {
    @Autowired
    MongoTemplate mongoTemplate;
    public List<Department> findallnames(String[] list){
        Query query = new BasicQuery(new Document("subdepartment",new Document("$all", list)));
        return mongoTemplate.find(query, Department.class);
    }

    public List<Department> findleaders(String position, String title){
        List<Document> documents = new ArrayList<>();
        documents.add(new Document("position",position));
        documents.add(new Document("title",title));
        Query query = new BasicQuery(new Document("leaders", new Document("$elemMatch",new Document("$and", documents))));
        return mongoTemplate.find(query, Department.class);
    }
    public void insertDepartment(Department department){
        mongoTemplate.insert(department);
    }
    public void  upsertLeader(Leader leader, String id) {
        Query query = new BasicQuery(new Document("_id", id));
        Update update = new Update();
        List<Leader> leaders = new ArrayList<>();
        leaders.add(leader);
        update.set("leaders", leaders);
        mongoTemplate.upsert(query, update ,Department.class);
    }
    public void  deleteDepartment(String name) {
        Query query = new BasicQuery(new Document("name", name));
        mongoTemplate.remove(query, Department.class);
    }
}
